<template>
    <div @mouseenter="clearTimer" @mouseleave="startTimer">
        <v-snackbar
            v-model="visible"
            :color="color || type"
            :top="y === 'top'"
            :left="x === 'left'"
            :bottom="y === 'bottom'"
            :right="x === 'right'"
            :multi-line="mode === 'multi-line'"
            :timeout="timeout"
            :vertical="mode === 'vertical'"
        >
            {{ text }}
            <v-btn dark color="info" text @click="close">
                关闭
            </v-btn>
        </v-snackbar>
    </div>
</template>

<script lang="ts">
import { VSnackbar, VBtn } from 'vuetify/lib';
import { Component, Vue } from 'vue-property-decorator';
import app from '@/main';
@Component({
    components: {
        VSnackbar,
        VBtn,
    },
})
export default class extends Vue {
    public visible = false;
    public y = 'top';
    public x = null;
    public mode = '';
    public timeout = 6000;
    public text = '';
    public color = null;
    public timer: number | null = null;
    public closed = false;
    public duration = this.timeout;
    public type = 'info';

    public close() {
        this.visible = false;
        this.closed = true;
        window.setTimeout(() => {
            // 从DOM里将这个组件移除
            this.$destroy();
            if (this.$el) {
                if (this.$el.parentNode) {
                    this.$el.parentNode.removeChild(this.$el);
                }
            }
        }, 500);
    }
    public clearTimer() {
        if (this.timer) {
            window.clearTimeout(this.timer);
        }
    }
    public startTimer() {
        if (this.duration > 0) {
            this.timer = window.setTimeout(() => {
                if (!this.closed) {
                    this.close();
                    this.duration = 0;
                }
            }, this.duration);
        }
    }
    public keydown(e: KeyboardEvent) {
        if (e.keyCode === 27 && !this.closed) {
            this.close();
        }
    }

    public mounted() {
        // app.$vuetify.theme.themes.light.primary = '#4caf50';
        this.visible = true;
        this.duration = this.timeout;
        this.startTimer();
        document.addEventListener('keydown', this.keydown);
    }
    public beforeDestroy() {
        document.removeEventListener('keydown', this.keydown);
    }
}
</script>
